package br.edu.granbery.indianostore.action;

import br.edu.granbery.indianostore.controller.Action;
import br.edu.granbery.indianostore.dao.DaoFactory;
import br.edu.granbery.indianostore.dao.UsuarioDao;
import br.edu.granbery.indianostore.model.Usuario;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CadastrarUsuarioAction implements Action {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		String nome = request.getParameter("txtNome");
		String sobrenome = request.getParameter("txtSobrenome");
		String cpf = request.getParameter("txtCPF");
		String login = request.getParameter("txtLogin");
		String senha = request.getParameter("txtSenha");
		String tipo = request.getParameter("txtTipo");
		
		RequestDispatcher view;
		if (nome.equals("") || sobrenome.equals("") || cpf.equals("")
				|| login.equals("") || senha == null || tipo.equals("")) {
			request.setAttribute("erro",
					"Preencha todos os campos corretamente");
		}else{
			HttpSession sessao = request.getSession(true);
			DaoFactory factory = (DaoFactory) sessao.getAttribute("factory");
			
			Usuario usuario = new Usuario();
			usuario.setNome(nome);
			usuario.setSobrenome(sobrenome);
			usuario.setCpf(cpf);
			usuario.setLogin(login);
			usuario.setSenha(senha);
			usuario.setTipo(tipo);
			
			UsuarioDao usuarioDao = factory.getUsuarioDao();
			factory.beginTransaction();
			if(usuarioDao.inserir(usuario)){
				request.setAttribute("sucess","Usuario cadastrado com sucesso.");
				factory.commit();
			}else{
				request.setAttribute("erro", "Erro ao cadastrar o usuario.");
				if (factory.hasTransaction()) {
					factory.stopTransaction();
				}
			}
			usuarioDao.destruir(usuario);
		}
		try {
			view = request.getRequestDispatcher("/View/Usuario/CadastrarUsuario.jsp");
			view.forward(request, response);
		} catch (ServletException ex) {
			Logger.getLogger(CadastrarUsuarioAction.class.getName()).log(
					Level.SEVERE, null, ex);
		}
	}
}
